/*
    i2cdriver.c - I2C driver implementation file
    Copyright (C) 1999-2004  Frodo Looijaard <frodol@dds.nl>, and
                             Mark D. Studebaker <mdsxyz123@yahoo.com>
    Copyright (C) 2004-2012  Jean Delvare <khali@linux-fr.org>
    Copyright (C) 2024  Huawei Technologies Co., Ltd.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    MA 02110-1301 USA.
*/

#include "i2cdriver.h"

int32_t i2c_init(int fd, int bus, int addr)
{
    if (bus < 0) {
        return -1;  /* Invalid bus number */
    }
    
    struct i2c_init_s init_data;
    init_data.drv_id = bus;  /* Use actual bus number */
    init_data.speed = 100;
    init_data.is_slave = 0;
    init_data.address = addr;
    init_data.sda_hold_ratio = 50;

    int32_t ret = ioctl(fd, I2C_CMD_INIT, &init_data);
    if (ret < 0) {
        return -1;  /* Unified error code */
    }
    return 0;  /* Success */
}

int32_t i2c_open(void)
{
    int32_t fd = open(DEVICE_NAME, O_RDWR);
    if (fd < 0)
    {
        return -1;
    }
    return fd;
}

int32_t i2c_close(int fd)
{
    if (fd < 0) {
        return -1;  /* Invalid file descriptor */
    }
    
    int32_t ret = close(fd);
    if (ret < 0) {
        return -1;  /* Error closing device */
    }
    return 0;  /* Success */
}

int32_t i2c_read(int fd, struct i2c_data_s *read_data, uint8_t *read_buf)
{
    if (read_data == NULL || read_buf == NULL)
    {
        return -1;
    }
    
    /* Create a copy to avoid modifying the input parameter */
    struct i2c_data_s data_copy = *read_data;
    data_copy.read_data = read_buf;          /* Set read buffer */
    int32_t ret = ioctl(fd, I2C_CMD_READ, &data_copy);
    if (ret < 0) {
        return -1;  /* Unified error code */
    }
    return 0;  /* Success */
}
